package service.impl.graph;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import model.GraphResult;
import model.GraphSearchCriteria;

import org.json.simple.JSONArray;

import service.impl.Converter;
import service.impl.JSONEncoder;

public class MethodGraphConstructor {

	public static JSONArray constructMethodGraph(List<GraphResult> graphResults, GraphSearchCriteria criteria) {
		if (criteria.getMethodId() != null) {
			return new JSONArray();
		}
		Map<String, Double> percentageByMethod = new HashMap<String, Double>();
		classifyByMethod(percentageByMethod, graphResults);
		return JSONEncoder.encodeMethodGraphData(percentageByMethod);
	}

	private static void classifyByMethod(Map<String, Double> prcntByMethod, List<GraphResult> graphResults) {
		// List of all learning methods, which percentage of use
		// is greater than 0%
		for (GraphResult result : graphResults) {
			String methodType = result.getMethodType();
			if (!prcntByMethod.containsKey(methodType)) {
				prcntByMethod.put(methodType, 1.0);
				continue;
			}
			prcntByMethod.put(methodType, prcntByMethod.get(methodType) + 1.0);
		}
		int allMethodsCount = graphResults.size();
		// Get percentage value of each used method
		for (String method : prcntByMethod.keySet()) {
			Double methodUsedTimes = prcntByMethod.get(method);
			Double percent = (methodUsedTimes * 100.0) / allMethodsCount;
			prcntByMethod.put(method, Converter.formatDouble(percent, 1));
		}
	}
}
